/**
 * 选票策略：交易量是昨天的1.2-2倍之间，vol5穿过，ma20穿过，连续4日macd指数增长
 * 函数调用：select * from getst(1) as st(date text,volume double precision,zf double precision,macd text,dz2 double precision,sdz double precision,code text,close double precision, mrj double precision,name text)
 */
create or replace function getst(days int) returns setof record as
$$
declare
rec record;
begin
  for rec in EXECUTE '
		select
		 b."date",b.volume,b.zf,b.macd,b.dz2,b.sdz,b.code,b."close",b."close"*0.99 as "mrj",
		s."name"
		from basic_data b left join stocks s on b.code=s.code 
		where 
		--b.macd::float8= 0
		to_date(b.date,''YYYY-MM-DD'') = getwd(current_date,'||days||')
		and b."close"*b.volume>100000--交易量大于一千万
		and b.macd != ''NaN'' --and b.macd::float8 > 0
		and b.volume/(select volume from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) > 1.5 --and b.volume/(select volume from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) <2
		and b.macd::float8 > (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) 
		and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) > (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+2||') and code=b.code)
		and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+2||') and code=b.code) > (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+3||') and code=b.code)
		and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+3||') and code=b.code) > (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+4||') and code=b.code)
		and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+4||') and code=b.code) < 0 
		and b.ma20<b.high
		and b.vol5< b.volume
		and b.low < b.ma20
		and (select low from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) < (select ma10 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) 
		order by  b.macd::float8 
		;' loop
    return next rec;
  end loop;
return;
end
$$
language 'plpgsql';